#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
__version__ = '1.0'
"""
    ***********************************
    *  @filename : Imports.py
    *  @Author : wshu
    *  @CodeDate : 2020/4/15 12:16
    *  @Software : PyCharm
    ***********************************
"""
import glob
import importlib
from os.path import isdir, basename, join, splitext

EXTENSIONS = '/**.py'

def get_categories(datasetpath):
    """
    得到所有分类，文件夹名称
    """
    cat_paths = [files for files in glob.glob(datasetpath + "\\*") if isdir(files)]
    cat_paths.sort()
    ui_mod = [basename(cat_path) for cat_path in cat_paths]
    return ui_mod

def get_files(path, baseui, extensions=EXTENSIONS):
    """
    返回分类路径path下的所有视频文件名,list
    """
    all_model = []
    if isinstance(path, list):
        for mod in path:
            if splitext(mod)[1] in extensions:
                mod_ui = glob.glob(baseui + mod + '/**.py')
                all_model.extend(mod_ui)
    else:
        all_model.extend([join(path, basename(fname)) for fname in glob.glob(path + "/*") if splitext(fname)[1] in extensions])
    return all_model


def filter_mod(module_list):
    """
    导入指定路径或者目录下的模块，并返回模块信息
    :return 模块信息字典
    if handler_name in PARAMETERS.keys():
        # print(PARAMETERS[handler_name])
        obj = ('/' + handler_name + ".tpy.*", fun, PARAMETERS[handler_name])
    else:
        obj = ('/' + handler_name + ".tpy.*", fun)
    """
    urls = []
    spaApi = {}
    _mod_set = []
    if isinstance(module_list, list):
        for mod_path in module_list:
            mod_name = mod_path.replace('/', '.').replace('\\', '.')[:-3]
            module = importlib.import_module(mod_name)
            # print(module)
            mod_set = []
            for elem in dir(module):
                # 获取用户自定义的函数和变量名称
                # print(elem)
                if not elem.startswith('__') and elem.endswith('Handler'):
                    f = eval('module.{}'.format(elem))
                    handler_path = str(f.__dict__['__module__'])
                    # print("test: ", handler_path)
                    if not str(f.__dict__['__module__']).startswith('tornado'):
                        handler_name = elem[:-7].lower()
                        # print("handler_name: ", handler_name)
                        obj = ('/' + handler_name, f)
                        spaApi[handler_name] = f
                        urls.append(obj)
    else:
        raise TypeError('[parse error] Must be a list type')
    return urls, spaApi